package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.Owner;
import com.hanserwei.community.entity.po.Repair;
import com.hanserwei.community.entity.request.repair.RepairQueryRequest;
import com.hanserwei.community.entity.request.repair.RepairSaveRequest;
import com.hanserwei.community.entity.vo.OwnerBriefVO;
import com.hanserwei.community.entity.vo.RepairVO;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.mapper.RepairMapper;
import com.hanserwei.community.service.OwnerService;
import com.hanserwei.community.service.RepairService;
import com.hanserwei.community.uitils.ThrowUtils;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class RepairServiceImpl extends ServiceImpl<RepairMapper, Repair> implements RepairService {

    private final OwnerService ownerService;

    @Override
    public Page<RepairVO> pageRepairs(RepairQueryRequest request) {
        Page<Repair> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<Repair> wrapper = buildQueryWrapper(request);
        Page<Repair> repairPage = page(page, wrapper);
        List<RepairVO> voList = convertToVOList(repairPage.getRecords());
        Page<RepairVO> voPage = new Page<>(repairPage.getCurrent(), repairPage.getSize(), repairPage.getTotal());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public RepairVO getRepairDetail(Integer id) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "维修工单ID参数错误！");
        Repair repair = getById(id);
        ThrowUtils.throwIf(repair == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "维修工单不存在！");
        List<RepairVO> list = convertToVOList(Collections.singletonList(repair));
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public boolean createRepair(RepairSaveRequest request) {
        validateSaveRequest(null, request);
        Repair repair = new Repair();
        BeanUtils.copyProperties(request, repair);
        boolean result = save(repair);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "新增失败！");
        return true;
    }

    @Override
    public boolean updateRepair(Integer id, RepairSaveRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ResponseCodeEnum.INVALID_PARAMETER, "维修工单ID参数错误！");
        validateSaveRequest(id, request);
        Repair repair = getById(id);
        ThrowUtils.throwIf(repair == null, ResponseCodeEnum.RESOURCE_NOT_FOUND, "维修工单不存在！");
        BeanUtils.copyProperties(request, repair);
        repair.setId(id);
        boolean result = updateById(repair);
        ThrowUtils.throwIf(!result, ResponseCodeEnum.SYSTEM_ERROR, "更新失败！");
        return true;
    }

    @Override
    public QueryWrapper<Repair> buildQueryWrapper(RepairQueryRequest request) {
        QueryWrapper<Repair> wrapper = new QueryWrapper<>();
        if (request == null) {
            return wrapper;
        }
        wrapper.eq(request.getId() != null && request.getId() > 0, "id", request.getId());
        wrapper.like(StringUtils.hasText(request.getRepairCode()), "com_id", request.getRepairCode());
        wrapper.eq(request.getOwnerId() != null && request.getOwnerId() > 0, "owner_id", request.getOwnerId());
        wrapper.eq(request.getStatus() != null, "status", request.getStatus());
        wrapper.ge(request.getReportTimeFrom() != null, "com_date", request.getReportTimeFrom());
        wrapper.le(request.getReportTimeTo() != null, "com_date", request.getReportTimeTo());
        wrapper.ge(request.getFinishTimeFrom() != null, "handle_date", request.getFinishTimeFrom());
        wrapper.le(request.getFinishTimeTo() != null, "handle_date", request.getFinishTimeTo());
        wrapper.like(StringUtils.hasText(request.getRemarks()), "remarks", request.getRemarks());
        if (StringUtils.hasText(request.getOwnerName())) {
            List<Integer> ownerIds = ownerService.lambdaQuery()
                    .like(Owner::getUserName, request.getOwnerName())
                    .select(Owner::getId)
                    .list()
                    .stream()
                    .map(Owner::getId)
                    .distinct()
                    .toList();
            if (ownerIds.isEmpty()) {
                wrapper.apply("1 = 0");
            } else {
                wrapper.in("owner_id", ownerIds);
            }
        }
        wrapper.orderBy(StringUtils.hasText(request.getSortField()), !"descend".equalsIgnoreCase(request.getSortOrder()), request.getSortField());
        return wrapper;
    }

    private void validateSaveRequest(Integer id, RepairSaveRequest request) {
        ThrowUtils.throwIf(request == null, ResponseCodeEnum.INVALID_PARAMETER, "参数错误！");
        ThrowUtils.throwIf(request.getOwnerId() == null || request.getOwnerId() <= 0, ResponseCodeEnum.INVALID_PARAMETER, "报修业主不能为空！");
        Owner owner = ownerService.getById(request.getOwnerId());
        ThrowUtils.throwIf(owner == null, ResponseCodeEnum.INVALID_PARAMETER, "报修业主不存在！");
        if (StringUtils.hasText(request.getRepairCode())) {
            Long duplicate = lambdaQuery()
                    .eq(Repair::getRepairCode, request.getRepairCode())
                    .ne(id != null && id > 0, Repair::getId, id)
                    .count();
            ThrowUtils.throwIf(duplicate != null && duplicate > 0, ResponseCodeEnum.INVALID_PARAMETER, "工单编号已存在！");
        }
        LocalDateTime reportTime = request.getReportTime();
        ThrowUtils.throwIf(reportTime == null, ResponseCodeEnum.INVALID_PARAMETER, "报修时间不能为空！");
        LocalDateTime finishTime = request.getFinishTime();
        if (reportTime != null && finishTime != null) {
            ThrowUtils.throwIf(reportTime.isAfter(finishTime), ResponseCodeEnum.INVALID_PARAMETER, "完成时间不能早于报修时间！");
        }
    }

    private List<RepairVO> convertToVOList(List<Repair> repairs) {
        if (CollectionUtils.isEmpty(repairs)) {
            return Collections.emptyList();
        }
        Set<Integer> ownerIds = repairs.stream()
                .map(Repair::getOwnerId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Integer, Owner> ownerMap = ownerIds.isEmpty() ? Collections.emptyMap() : ownerService.listByIds(ownerIds).stream()
                .collect(Collectors.toMap(Owner::getId, owner -> owner));

        return repairs.stream().map(repair -> {
            RepairVO vo = new RepairVO();
            BeanUtils.copyProperties(repair, vo);
            vo.setRepairCode(repair.getRepairCode());
            vo.setOwnerId(repair.getOwnerId());
            if (repair.getOwnerId() != null) {
                Owner owner = ownerMap.get(repair.getOwnerId());
                if (owner != null) {
                    vo.setOwner(toOwnerBrief(owner));
                }
            }
            return vo;
        }).toList();
    }

    private OwnerBriefVO toOwnerBrief(Owner owner) {
        if (owner == null) {
            return null;
        }
        return OwnerBriefVO.builder()
                .id(owner.getId())
                .name(owner.getUserName())
                .tel(owner.getTel())
                .houseId(owner.getHouseId())
                .build();
    }
}
